<?php
class ModulesAction extends CommonAction {
	public function _initialize(){
		parent::_initialize();
		$info = $this->dao -> where(array('id' => $this->_request('id'))) -> find();
		//$subListpid = $tm -> where(array('filename' => $info['filename'], 'template_id' => $this->getTemplateid())) -> find();
		//只有空盒子可以有子模块
		//dump(intval($info['site_id']) != intval($this->siteid));
		
		if(intval($info['site_id']) != intval($this->siteid) && (strtolower(ACTION_NAME) != 'ajaxinsert' && strtolower(ACTION_NAME) != 'dosort')){
			if(!session(C('ADMIN_AUTH_KEY') )){
			    $this->error('您没有权限'.print_r($info,true));exit();
			}
		}
		if($this->_get('templatefilename')){
			$this->assign('templatefilename',$this->_get('templatefilename'));
			$this->templatefilename = $this->_get('templatefilename');
		}else{
			$this->assign('templatefilename','index');
			$this->templatefilename = 'index';
		}
		
		
	}
	
	//重写排序
	public function dosort(){
		$ids = array();
		$data = explode(',', $this->_post('sort'));
		foreach($data as $v){
			$mid = explode('_', $v);
			$ids[] = $mid[0];
		}
		$this->dao -> where(array('id'=>array('in',$ids),'pages_id' => 0)) -> data(array('pages_id' => $this->_post('id'))) ->save();
		$this->dao -> where(array('id'=>array('not in',$ids),'pages_id' => $this->_post('id'))) -> data(array('pages_id' => 0)) ->save();
		
		parent::dosort();
	}
	
	function index(){
		$map = array('pid'=>0,'site_id'=>$this->siteid,'templatefilename'=>$this->templatefilename, 'template_id' => $this->getTemplateid());
		$this->listmap = $map;
		$this->listorder="sort";
        parent::_list();
		$list=$this->list;
		foreach($list as $k=>$v){
			$list[$k]['sub']=$this->dao->getListToArray1($v['id'],$this->siteid);
		}
		//模板文件列表
		$this->assign('TemplateFileList',$this->getTemplateList());
		$this->assign('list',$list);
		$this->display();
	}
	
	public function add(){
		if($this->_get('pid')){
			//询查是否存在该模块的子模块，如果不存提示用户不能不能添加
			$pm = $this->where(array('id' => $this->_get('pid')))->find();
			if(!is_array($pm)){
				$this->error('当前模块没有可添加的子模块！');exit;
			}
			$this->assign('pid', $this->_get('pid'));
		}
		$modulesList = $this->getModules();
		$this->assign('modulesList', $modulesList);
		 
		if(isset($_GET['sort'])){
			$this->sort = intval($_GET['sort']);
			$this->display('addsort');exit();
		}else{
		    $this->display();
		} 
	}
	
	private function object_array($array){
	   if(is_object($array))
	   {
		$array = (array)$array;
	   }
	   if(is_array($array))
	   {
		foreach($array as $key=>$value)
		{
		 $array[$key] = $this->object_array($value);
		}
	   }
	   return $array;
	}
	
	
	public function edit(){
		$tm = D('Template_modules');
		$info = $this->dao -> where(array('id' => $this->_get('id'))) -> find();
		
		//文章栏目
		$category = D('Category');
		$category_list=$category->where(array('pid'=>0,'site_id'=>$this->siteid))->select();
		
		foreach($category_list as $k=>$v){
			$category_list[$k]['sub']=$category->getListToArray1($v['id'],$this->siteid);
		}
		$this->assign('category_list',$category_list);
		//文章栏目结束
		
		
		
		if($info['type'] == 6){
			$map['type'] = array('neq',6);
			$map['template_id'] = $this->getTemplateid();
			$tsubList = $tm ->where($map)->order('sort')->select();
			$this->assign('tsubList', $tsubList);
			$pasteList = F('pasteList');
			
			foreach($pasteList as $k => $v){
				if($v['type'] == 6){
					unset($pasteList[$k]);
				}

			}
			
			
			$this->assign('pasteList', $pasteList);
		}
		//万能表单
		if($info['type'] == 16){
			$formList = D('Form') -> where(array('site_id' => $this->siteid)) -> select();
			$this->assign('formList', $formList);
		}
		
		
		if($info['type'] == 14){ 
			$map['type'] = array('not in','6,14');
			$map['template_id'] = $this->getTemplateid();
			$tsubList = $tm ->where($map)->order('sort')->select();
			
			
			$this->assign('tsubList', $tsubList);
			
			$pasteList = F('pasteList');
			
			foreach($pasteList as $k => $v){
				if($v['type'] == 6 || $v['type'] == 14){
					unset($pasteList[$k]);
				}

			}
			
			
			$this->assign('pasteList', $pasteList);
		}
		//News列表
		if($info['type'] == 1 ||$info['type'] == 13 || $info['type'] == 2 || $info['type'] == 12 || $info['type'] == 10){
			$this->newsList = unserialize($info['content']);
		}
		//如果是轮播图
		if($info['type'] == 3){
			$this->banner = unserialize($info['content']);
		}
		$subList = $this->dao -> where(array('pid' => $info['id'],'template_id' => $this->getTemplateid())) -> order('sort') ->select();
		$this->assign('subList', $subList);
		 
		parent::edit();
	}
	
	
	//ajax添加模块
	public function addModules(){
		$_POST['site_id'] = $this->siteid;
		$_POST['template_id'] = $this->getTemplateid();
		
		if($jumpUrl == ''){
			$jumpUrl = (session('jumpUrl'))&&session('jumpUrl')!='') ? session('jumpUrl') : U('Admin/' . MODULE_NAME . '/index');
		}
        
        if ($this->dao->create($data)) {
            $result = $this->dao->add();
            if (false !== $result) {
				$data['status'] = 1;
				$data['info'] = '操作成功';
				$data['url'] = $jumpUrl;
				$data['img_url'] = $_POST['img_url'];
				$data['id'] = $result;
				echo json_encode($data);exit;
               // $this->success('', $jumpUrl);
            } else {
                $this->error($this->dao->getError());
            }
        } else {
            $this->error($this->dao->getError());
        }
	}
	
	
	private function getModules(){
		//获取当前使用的模板ID
		$template_id = $this->getTemplateid();
		$Category=D('Template_modules');
		$list = $Category -> where(array('template_id' => $template_id)) ->select();
		return $list;
	}
	
	private function getTemplateid(){
		$one = M('Site') -> where(array('id' => $this->siteid))->find();
		return $one['template_id'];
	}
	private function getTemplateList(){
		$one = M('Template') -> where(array('id' => $this -> getTemplateid())) -> find();
		return $this->object_array(json_decode($one['templateFileList']));
	}
	public function insert(){
		$_POST['site_id'] = $this->siteid;
		$_POST['template_id'] = $this->getTemplateid();
		parent::insert();
	}
	
	//Ajax添加模块到页面
	public function ajaxInsert(){
		if($this->_post('filename') == ''){
			$ret['status'] = 0;
			exit(json_encode($ret));
		}
		$_POST['site_id'] = $this->siteid;
		$_POST['template_id'] = $this->getTemplateid();
		$this->dao -> create();
		$id = $this->dao -> add();
		if($id > 0){
			//得到模块设置
			$this->initView();
			$ret['status'] = 1;
			$ret['id'] = $id;
			$ret['data'] = $this->dao -> getModulesSource($id, $this->view);
			$ret['deleteUrl'] = U('Admin/Modules/delete',array('id'=>$id));
			$ret['settingUrl'] = U('Admin/Modules/edit',array('id'=>$id));
			exit(json_encode($ret));
		}else{
			$this->error($this->dao -> getError());
		}
	}
	
	
	//获取一个模块
	public function getOne(){
		
		$this->initView();
		
		$ret['status'] = 1;
		$ret['id'] = $id;
		$ret['data'] = $this->dao -> getModulesSource($this->_post('id'), $this->view);
		exit(json_encode($ret));
	}
	//更新
	public function update(){
		//栏目图片轮播
		$info = $this->dao->where(array('id' => $this->_post('id')))->find();
		if(!$this->_post('bannertitle')){
			if($info['type'] == 3){
				$_POST['content'] = '';
			}
		}
		
		
		
		
		if($this->_post('modulesContent')){
			$list = $_POST['modulesContent'];
			$newsdb = D('News');
			$catedb = D('Category');
			$pcatedb = D('Product_category');
			$pdb = D('Product');
			//$data = $db -> where(array('id' => $id)) -> find();
			if($data !== false){
				//文章表
				if($info['type'] == 1 || $info['type'] == 2 || $info['type'] == 10){
					
					$ret = array();
					foreach($list as $v){
						$v = explode('_', $v);
						if($v[0] == 0){
							$one = $newsdb->where(array('id' => $v[1], 'site_id' => $this->siteid))-> Field('id,title,module,img_url,datetime,name')->find();
						}else{
							$one = $pdb->where(array('id' => $v[1], 'site_id' => $this->siteid))-> Field('id,title,module,img_url,create_time,name,price,salecount')->find();
						}
						if($one){
							$ret[] = $one;
						}
					}
					
				}
				
				//分类列表
				if($info['type'] == 12){
					
					$ret = array();
					foreach($list as $v){
						$v = explode('_', $v);
						if($v[0] == 0){
							$one = $catedb->where(array('id' => $v[1], 'site_id' => $this->siteid)) -> Field('id,title,module,img_url,datetime,name') ->find();
						}else{
							$one = $pcatedb->where(array('id' => $v[1], 'site_id' => $this->siteid)) -> Field('id,title,module,img_url,datetime,name')->find();
						}
						if($one){
							$ret[] = $one;
						}
					}
					
				}
			}
			$_POST['content'] = serialize($ret);
		}else{
			if($info['type'] == 1 || $info['type'] == 2 || $info['type'] == 10 || $info['type'] == 12){
				$_POST['content'] = '';
			}
		}
		
		
		
		
		
		
		
		
		
		if($this->_post('bannertitle')){
			$data=array();
			$link=$this->_post('link');
			$img_url = $this->_post('img_path');
			$title = $this->_post('bannertitle');
			foreach($title as $k => $v){
				$data[$k]['title'] = $title[$k];
				$data[$k]['img_url'] = $img_url[$k];
				$data[$k]['link'] = $link[$k];
			}
			$_POST['content'] = serialize($data);
		}
		$this->dao->create();
		$result = $this->dao -> where(array('id' => $this->_post('id'))) -> save();
		if($result !== false){
			
			$ret['status'] = 1;
			$ret['data'] = $this->_post('id');
			exit(json_encode($ret));
			
		}else{
			$this->error($this -> dao ->getError());
		}
		
	}
	public function delete(){
		if($this->_get('id')){
			$parentisex = $this -> dao -> where(array('pid' => $this->_get('id'))) -> find();
			if($this->_post('deleteAll') == 1){
				$this->dao->deleteAll($this->_get('id'));
				$this->success('删除成功');
				exit;
			}
			if(is_array($parentisex)){
				$ret['status'] = 0;
				$ret['info'] = '该模块包含了子类，如果您确定要删除请按确认！'; 
				$ret['error'] = '1';
				$ret['id'] = $this->_get('id');
				exit(json_encode($ret));
				//$this->error('请先删除子级模块');exit();
			} 
			parent::delete();
		}
	}
	//粘贴模块
	public function pasteModules(){
		if($this->_post('id')){
		   $_POST['id'] = $this->dao -> copyself($this->siteid,$this->siteid,array('id' => $this->_post('id')),intval($this->_post('pid')),intval($this->_post('pages_id')));
		   $this->getOne();
		}
	}
	
	//复制样式
	public function copystyle(){
		if($this->_post('id')){
			$source = $this -> dao -> where(array('id' => $this->_post('id'))) -> find();
			if(isset($_POST['all'])){
				//复制一个模块，包含子模块
				//生成粘贴记录返回前端
				$pasteList = F('pasteList');
				if(!$pasteList){
					$pasteList[] = $source;
				}
				F('pasteList',$pasteList);
				$source['status'] = 1;
				echo json_encode($source);
				
				
				unset($source['id']);
				unset($source['type']);
				unset($source['templatefilename']);
				unset($source['filename']);unset($source['template_modules_id']);
				unset($source['img_url']);
				unset($source['pid']);
				unset($source['pages_id']);
				F('modules_style',$source);
				exit;
			}else{
				unset($source['pages_id']);
				unset($source['content']);
				unset($source['id']);
				unset($source['data']);
				unset($source['title']);
				unset($source['pid']);
				unset($source['type']);
				unset($source['filename']);
				unset($source['templatefilename']);
				unset($source['template_modules_id']);
				unset($source['img_url']);
			}
			F('modules_style',$source);
			$this->success('复制成功');
		}else{
			$this->error('参数错误');
		}
	}
	
	//粘贴样式
	public function parsestyle(){
		if($this->_post('id')){
			$data = F('modules_style');
			$ret = $this -> dao -> where(array('id' => $this->_post('id'))) -> data($data) -> save();
			$this->success('粘贴成功');
		}else{
			$this->error('参数错误');
		}
	}
	
	//删除列表信息
	public function removeListInfo(){
		if($this->_post('news_id')){
			$id = $this->_post('news_id');
			$module = $this->_post('module');
			$ret = $this->dao -> where(array('id' => $this->_post('id'))) -> find();
			$data = unserialize($ret['content']);
			$arr = array();
			foreach($data as $k=> $v){
				
				if($id != $v['id'] || $module != $v['module']){
					$arr[] = $v;
				}
			}
			
			$upret = $this->dao->where(array('id' => $this->_post('id')))->data(array('content' => serialize($arr)))-> save();
			if($uparr !== false){
				$this->success('删除成功');
			}else{
				$this->error($this-> getError());
			}
			
		}
	}
	
	
	public function copy(){
		$map['templatefilename'] = $this->_post('templatefilename');
		$totemplatefilename = $this->_post('totemplatefilename');
		$map['template_id'] = $this->getTemplateid();
		$map['site_id'] = $this->siteid;
		$map['pid'] = 0;
		if($this->_post('isdel') > 0){
			$this->dao -> where(array('site_id' => $this->siteid,'templatefilename' => $totemplatefilename, 'template_id' => $map['template_id']))->delete();
		}
		$this->dao->copyself($this->siteid,$this->siteid,$map,0,$totemplatefilename);
	}
	
	//列表排序
	public function sortListInfo(){
		if($this->_post('id')){
			$modules_id = $this->_post('id');
			$sortdata = explode(',',$this->_post('sort'));
			$data = $this->dao -> where(array('id' => $modules_id)) ->Field('content') -> find();
			$list = unserialize($data['content']);
			if(count($list) != count($sortdata)){
				$this->error('数据错误,请刷新后重试');exit();
			}
			if(is_array($list)){
				$ret = array();
				foreach($sortdata as $v){
					$ret[] = $list[$v];
				}
				$sd = serialize($ret);
				$rq = $this -> dao ->where(array('id' => $modules_id)) ->data(array('content'=>$sd)) -> save();
				if($rq !== false){
					$this->success('更新成功');
				}else{
					$this->error($this->dao -> getError());
				}
			}else{
				$this->error('模块类型错误');
			}
		}
	}
}